package com.gyms.adapter;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.v7.widget.RecyclerView;
import android.text.SpannableStringBuilder;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.classic.okhttp.beans.HVMyOrderInfoBean;
import com.classic.okhttp.beans.HVOrderCardBean;
import com.classic.okhttp.beans.HVProductOrderFieldBean;
import com.classic.okhttp.beans.HVVenueOrderFieldBean;
import com.classic.okhttp.enums.Enum;
import com.classic.okhttp.zmoumall.utils.ToastUtil;
import com.gyms.R;
import com.gyms.activity.GymDetailActivity;
import com.gyms.constant.Constants;
import com.gyms.manager.OrderManger;
import com.gyms.manager.StateUtils;

import java.util.List;

import click.OnRecyclerViewItemClick;
import utils.DateUtil;
import utils.DecimalUtils;
import utils.StringUtils;
import utils.TimeTools;

/**
 * ltx on 2016/11/22 14:42
 * 我的订单adapter
 */
public class MyOrderAdapter extends RecyclerView.Adapter<MyOrderAdapter.MyOrderViewHolder> {
    private Context mContext;
    private LayoutInflater mLayoutInflater;
    private List<HVMyOrderInfoBean> mMyOrderList;
    //订单类型 (1场馆  2产品)
    private final static int GYM = 1;
    private final static int PRODUCT = 2;

    private OnRecyclerViewItemClick mOnRecyclerViewItemClick;
    //用于退出activity,避免countdown，造成资源浪费。
    private SparseArray<CountDownTimer> countDownMap;


    public MyOrderAdapter(Context mContext) {
        this.mContext = mContext;
        mLayoutInflater = LayoutInflater.from(mContext);
        countDownMap = new SparseArray<>();
    }

    /**
     * 清空资源
     */
    public void cancelAllTimers() {
        if (countDownMap == null) {
            return;
        }
        for (int i = 0,length = countDownMap.size(); i < length; i++) {
            CountDownTimer cdt = countDownMap.get(countDownMap.keyAt(i));
            if (cdt != null) {
                cdt.cancel();
            }
        }
    }

    /**
     * 填充数据
     *
     * @param mHVMyOrderInfoBean 订单的bean
     * @param state 订单状态
     */

    private void doFullView(MyOrderViewHolder mViewHolder, HVMyOrderInfoBean mHVMyOrderInfoBean, int state) {
        double mAllPrice = mHVMyOrderInfoBean.getActualPrice();//总价
        HVOrderCardBean mHVMyOrderInfoBeanCard=mHVMyOrderInfoBean.getCard();
        mAllPrice=OrderManger.getActualPrice(mAllPrice,mHVMyOrderInfoBeanCard);
        mViewHolder.mTvOrderPrice.setText( new SpannableStringBuilder("实付：").append(DecimalUtils.setPriceStyle(mContext,mAllPrice,R.dimen.price_text_size_13,R.dimen.price_text_size_11,true)));//设置总价
        int orderType = mHVMyOrderInfoBean.getOrderType().value;//订单类型
        mViewHolder.mTvGymName.setText(mHVMyOrderInfoBean.getVenueName());
        mViewHolder.mTvOrderStaue.setText(OrderManger.getOrderStatus(state));
        if (mHVMyOrderInfoBean.getOrderState() != Enum.EnumOrderState.Nopay ) {//已支付或者超市 隐藏支付按钮
            mViewHolder.mTvPay.setVisibility(View.GONE);
        }else{
            mViewHolder.mTvPay.setVisibility(View.VISIBLE);
        }
        mViewHolder.mTvProjectName.setText(mHVMyOrderInfoBean.getProjectName());
        mViewHolder.mTvProjectName.setVisibility(StringUtils.isNull(mHVMyOrderInfoBean.getProjectName()) ? View.GONE : View.VISIBLE);
        //场地子订单
        List<HVVenueOrderFieldBean> orderField = mHVMyOrderInfoBean.getOrderField();
        //产品子订单
         HVProductOrderFieldBean orderProduct=mHVMyOrderInfoBean.getOrderProduct();
        mViewHolder.mLlOrderList.removeAllViews();
        addLayout(orderType, orderField,orderProduct, mViewHolder);
    }

    /**
     * @param orderType   //订单类型 (1场馆  2产品)
     * @param orderField  //预定的子列表
     * @param orderProduct 产品子列表
     * @param mViewHolder mViewHolder
     */

    private void addLayout(int orderType, List<HVVenueOrderFieldBean> orderField, HVProductOrderFieldBean orderProduct, MyOrderViewHolder mViewHolder) {
            //累计总价格

        if (orderType == GYM) {//场馆
            for (HVVenueOrderFieldBean mHVVenueOrderFieldBean : orderField) {
                View childView = View.inflate(mContext,R.layout.ll_child_field, null);
                TextView mTvWeek = (TextView) childView.findViewById(R.id.tv_order_week);
                TextView mTvDay = (TextView) childView.findViewById(R.id.tv_order_date);
                TextView mTvTime = (TextView) childView.findViewById(R.id.tv_order_time);
                TextView mTvFieldName = (TextView) childView.findViewById(R.id.tv_field_name);
                mTvWeek.setText(DateUtil.getWeek(mHVVenueOrderFieldBean.getStartTime()));
                mTvDay.setText(String.format(mContext.getResources().getString(R.string.str_kuohao), DateUtil.stampToDate(mHVVenueOrderFieldBean.getStartTime())));
                mTvTime.setText(mContext.getString(R.string.str_order_item_time,DateUtil.intToHour(mHVVenueOrderFieldBean.getStartTime()),DateUtil.intToHour(mHVVenueOrderFieldBean.getEndTime())));
                mTvFieldName.setText(mHVVenueOrderFieldBean.getFieldName());
                mViewHolder.mLlOrderList.addView(childView);
            }
        }else if(orderType==PRODUCT){//产品
                int num=orderProduct.getNumber();
                TextView mProductChildView= (TextView) View.inflate(mContext,R.layout.ll_child_product, null);
                 mProductChildView.setText(mContext.getString(R.string.str_order_item_product_num,orderProduct.getProductName(),String.valueOf(num)));
                 mViewHolder.mLlOrderList.addView(mProductChildView);
        }

    }

    public void setMyOrderList(List<HVMyOrderInfoBean> myOrderList) {
        mMyOrderList = myOrderList;
        notifyDataSetChanged();
    }

    @Override
    public MyOrderViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
       View  mView = mLayoutInflater.inflate(R.layout.item_my_order, parent, false);
        return new MyOrderViewHolder(mView);
    }

    @Override
    public void onBindViewHolder(MyOrderViewHolder holder, int position) {
        HVMyOrderInfoBean mHVMyOrderInfoBean = mMyOrderList.get(position);
        holder.mTvGymName.setTag(position);
        holder.itemView.setTag(position);
        int state=mHVMyOrderInfoBean.getOrderState().value;//订单状态
        doFullView(holder,mHVMyOrderInfoBean,state);

        int mOverTime=mHVMyOrderInfoBean.getPayOverTime()*1000;
        boolean isNotPay=StateUtils.isNotPay(state);//是否是未付款
        doCountDown(holder,mOverTime,isNotPay);
    }

    /**
     * 开始倒计时
     * @param holder holder
     * @param mOverTime 倒计时的时间
     * @param isNotPay 是否是未付款
     */

    private void doCountDown(final MyOrderViewHolder holder, int mOverTime, boolean isNotPay) {
        //将前一个缓存清除
        if (holder.countDownTimer != null) {
            holder.countDownTimer.cancel();
        }
        if (mOverTime > 0 && isNotPay) {
            holder.mTvLeftTime.setVisibility(View.VISIBLE);
            holder.countDownTimer = new CountDownTimer(mOverTime, 1000) {
                public void onTick(long millisUntilFinished) {
                    holder.mTvLeftTime.setText(TimeTools.getCountTimeByLong(millisUntilFinished));
                }
                public void onFinish() {
                    holder.mTvLeftTime.setText("已超时");
                    holder.mTvOrderStaue.setText("已取消");
                    holder.mTvPay.setVisibility(View.GONE);
                }
            }.start();
            countDownMap.put(holder.mTvLeftTime.hashCode(), holder.countDownTimer);
        } else {
            holder.mTvLeftTime.setVisibility(View.GONE);//没有支付就显示或者隐藏
            holder.mTvPay.setVisibility(View.GONE);
        }
    }

    @Override
    public int getItemCount() {
        return null == mMyOrderList ? 0 : mMyOrderList.size();
    }

    public void setOnRecyclerViewItemClick(OnRecyclerViewItemClick onRecyclerViewItemClick) {
        mOnRecyclerViewItemClick = onRecyclerViewItemClick;
    }

    class MyOrderViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
        private TextView mTvGymName;
        private TextView mTvProjectName;
        private TextView mTvOrderStaue;
        private LinearLayout mLlOrderList;
        private TextView mTvOrderPrice;
        private TextView mTvPay;
        private TextView mTvLeftTime;
        private CountDownTimer countDownTimer;
        private MyOrderViewHolder(View itemView) {
            super(itemView);
            mTvGymName= (TextView) itemView.findViewById(R.id.tv_gym_name);
            mTvProjectName= (TextView) itemView.findViewById(R.id.tv_project_name);
            mTvOrderStaue= (TextView) itemView.findViewById(R.id.tv_order_staue);
            mLlOrderList= (LinearLayout) itemView.findViewById(R.id.ll_order_list);
            mTvOrderPrice= (TextView) itemView.findViewById(R.id.tv_order_price);
            mTvPay= (TextView) itemView.findViewById(R.id.tv_pay);
            mTvLeftTime= (TextView) itemView.findViewById(R.id.tv_left_time);
            mTvGymName.setOnClickListener(this);
            itemView.setOnClickListener(this);
        }

        @Override
        public void onClick(View v) {
            int pos= (int) v.getTag();
            switch (v.getId()){
                case R.id.tv_gym_name://跳转场馆详情
                    HVMyOrderInfoBean myOrderInfoBean=mMyOrderList.get(pos);
                    if(StringUtils.isNull(myOrderInfoBean)){
                        return;
                    }
                    boolean isGymOnline=myOrderInfoBean.getVenueState();
                    if(isGymOnline){
                        Intent intent=new Intent(mContext, GymDetailActivity.class);
                        Bundle mBundle=new Bundle();
                        String mVenueId=myOrderInfoBean.getVenueId();
                        mBundle.putString(Constants.FLAG_INTENT_VENUEID, mVenueId);
                        intent.putExtras(mBundle);
                        mContext.startActivity(intent);
                    }else{
                        ToastUtil.showToast(mContext,"该场馆已经下架");
                    }

                    break;

                case R.id.ll_my_order_layout://onItemClick
                    if(null!=mOnRecyclerViewItemClick){
                        mOnRecyclerViewItemClick.onRecyclerItemClick((RecyclerView) v.getParent(),pos);
                    }
                    break;
            }
        }
    }
}
